﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace Jumpton.SFA.Server.BusinessRule
{
    interface IBusinessLogic
    {
        /// <summary>
        /// 根据主键来获取该条数据
        /// </summary>
        /// <param name="ID">主键</param>
        /// <returns>返回对象实体</returns>
        Object Load(decimal ID);
        /// <summary>
        /// 根据唯一性代码来返回该对象
        /// </summary>
        /// <param name="Code">唯一性代码</param>
        /// <returns>返回对象实体</returns>
        Object LoadByCode(string Code);
        /// <summary>
        /// 根据条件来获取一组对象集合
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns>对象集合</returns>
        Object LoadWithCondition(string Condition);
        /// <summary>
        /// 保存对象
        /// </summary>
        /// <param name="obj">需要保存的对象</param>
        void Save(Object obj);

    }
    public abstract class BusinessLogic
    {
        protected string message;
        protected Jumpton.Common.DatabaseType dbType;

        public string Message
        {
            get
            {
                string msg = message;
                message = "";
                return msg;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="time">需要转换的时间</param>
        /// <returns>返回yyyyMMddHHmmss格式的字符串</returns>
        public static String GetDateTimeString(DateTime time)
        {
            return time.ToString("yyyyMMddHHmmss");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="time">需要转换的时间</param>
        /// <returns>返回yyyyMMddHHmmss格式的字符串</returns>
        public static String GetShortDateTimeString(DateTime time)
        {
            return time.ToString("yyyyMMdd");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="time">需要转换的时间</param>
        /// <returns>返回yyyyMMddHHmmss格式的长整型</returns>
        public static long GetDateTimeLong(DateTime time)
        {
            return long.Parse(GetDateTimeString(time));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="time">需要转换的时间</param>
        /// <returns>返回yyyyMMddHHmmss格式的精度型</returns>
        public static decimal GetDateTimeDecimal(DateTime time)
        {
            return decimal.Parse(GetDateTimeString(time));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="datetime">需要转换的日期时间字符串</param>
        /// <returns>返回去除/、-、：分隔符的精度型</returns>
        public static decimal GetStringDateTimeDecimal(string datetime)
        {
            datetime = datetime.Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
            return decimal.Parse(datetime);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="time">需要转换的时间</param>
        /// <returns>返回制定fromat格式的字符串</returns>
        public static String GetDateTimeString(DateTime time,string fromat)
        {
            return time.ToString(fromat);
        }
        /// <summary>
        /// 将日期字符串转换成指定格式日期字符串
        /// </summary>
        /// <param name="time"></param>
        /// <param name="sourceformat">源格式</param>
        /// <param name="targetformat">目标格式</param>
        /// <returns>返回指定格式字符串</returns>
        public static string GetDateTime(string time,string sourceformat,string targetformat)
        {
            
            try
            {
                if (sourceformat == "")
                    sourceformat = "yyyyMMddHHmmss";
                if (targetformat == "")
                    targetformat = "yyyy-MM-dd";
                time= DateTime.ParseExact(time, sourceformat, global::System.Globalization.CultureInfo.CurrentCulture
                    , global::System.Globalization.DateTimeStyles.None).ToString(targetformat);
            }
            catch(Exception ex) {
                time="";
            }
            return time;
        }

        /// <summary>
        /// 根据时间参数的长度来判断，容易出错，格式要规范
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string GetDateTime(string time)
        {
            string sourceformat = "";
            string targetformat = "";
            if (time.Length == 8)
            {
                sourceformat = "yyyyMMdd";
                targetformat = "yyyy-MM-dd";
            }
            else if (time.Length == 12)
            {
                sourceformat = "yyyyMMddHHmm";
                targetformat = "yyyy-MM-dd HH:mm";
            }
            else if (time.Length == 14)
            {
                sourceformat = "yyyyMMddHHmmss";
                targetformat = "yyyy-MM-dd HH:mm:ss";
            }

            try
            {
                if (sourceformat == "")
                    sourceformat = "yyyyMMddHHmmss";
                if (targetformat == "")
                    targetformat = "yyyy-MM-dd";
                time = DateTime.ParseExact(time, sourceformat, global::System.Globalization.CultureInfo.CurrentCulture
                    , global::System.Globalization.DateTimeStyles.None).ToString(targetformat);
            }
            catch (Exception ex)
            {
                time="";
            }
            return time;
        }
        //计算两个日期日期的时间差
        public static  string DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            string dateDiff = "";
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();


                if (ts.Days != 0) dateDiff += ts.Days.ToString() + "天";
                if (ts.Hours != 0) dateDiff += ts.Hours.ToString() + "小时";
                if (ts.Minutes != 0) dateDiff += ts.Minutes.ToString() + "分钟";
                dateDiff += ts.Seconds.ToString() + "秒";

            }
            catch
            {

            }
            return dateDiff;
        }
       
        /// <summary>
        /// 数据库类型
        /// </summary>
        public Jumpton.Common.DatabaseType DbType
        {
            get
            {
                return Jumpton.Data.ConnectionProviderFactory.Create().DatabaseType;
            }

        }

       

        protected int GetMaxIntValue(string tableName, string columnName)
        {
            int max = 0;
            string sql = "select max(" + columnName + ") from " + tableName + "";
            object o = Jumpton.Data.SqlData.ExecuteScalar(sql);
            if (o != null)
            {
                int.TryParse(o.ToString(), out max);
            }
            return max;
        }

        public static string getNewImageName()
        {
            Random r=new Random();
            return DateTime.Today.ToString("yyyyMMddHHmmss") + r.Next(1, 1000) + r.Next(1, 1000);
        }

        /// <summary>
        /// 定位纠偏
        /// </summary>
        /// <param name="lat">纬度</param>
        /// <param name="lon">经度</param>
        /// <returns></returns>
        public static string Correct(string lat, string lon)
        {
            string str = null;
            String url = "http://www.anttna.com/goffset/goffset1.php?lat={0}&lon={1}";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(string.Format(url, lat, lon)));
                req.Timeout = 30 * 1000;
                req.Method = "GET";
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
               // global::System.Threading.Thread.Sleep(1000);
                byte[] data = new byte[res.ContentLength];
                res.GetResponseStream().Read(data, 0, data.Length);
                str = global::System.Text.UTF8Encoding.UTF8.GetString(data, 0, data.Length).Trim('\n');
            }
            catch (Exception ex)
            {
                str = lat + "," + lon;
                //Logger.Writer("\n ex.Message:" + ex.Message + "\n ex.StackTrace:" + ex.StackTrace, LoggerType.Exception);
                throw;
            }
            return str;

        }

        public static string getWeekDay()
        {
            string weekday = "0";
            switch (DateTime.Now.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    weekday = "1";
                    break;
                case DayOfWeek.Tuesday:
                    weekday = "2";
                    break;
                case DayOfWeek.Wednesday:
                    weekday = "3";
                    break;
                case DayOfWeek.Thursday:
                    weekday = "4";
                    break;
                case DayOfWeek.Friday:
                    weekday = "5";
                    break;
                case DayOfWeek.Saturday:
                    weekday = "6";
                    break;
                case DayOfWeek.Sunday:
                    weekday = "7";
                    break;
            }
            return weekday;
        }
    }
}
